<template>
  <div class="exam-result">
    <div class="result-header">
      <h2>考试成绩</h2>
      <div class="header-actions">
        <el-button @click="exportResults">
          <el-icon><Download /></el-icon>
          导出成绩
        </el-button>
      </div>
    </div>

    <!-- 成绩统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" v-for="stat in statistics" :key="stat.label">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon :size="32"><component :is="stat.icon" /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stat.value }}</div>
              <div class="stat-label">{{ stat.label }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成绩筛选 -->
    <el-card class="filter-card">
      <el-form inline>
        <el-form-item label="考试">
          <el-select v-model="filterForm.examId" placeholder="选择考试" clearable style="width: 200px">
            <el-option
              v-for="exam in exams"
              :key="exam.id"
              :label="exam.title"
              :value="exam.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="filterForm.classId" placeholder="选择班级" clearable style="width: 150px">
            <el-option
              v-for="cls in classes"
              :key="cls.id"
              :label="cls.name"
              :value="cls.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分数范围">
          <el-input-number v-model="filterForm.minScore" placeholder="最低分" :min="0" :max="100" />
          <span style="margin: 0 8px;">-</span>
          <el-input-number v-model="filterForm.maxScore" placeholder="最高分" :min="0" :max="100" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterResults">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 成绩列表 -->
    <el-card class="result-list-card">
      <template #header>
        <h3>成绩列表</h3>
      </template>

      <el-table :data="examResults" v-loading="loading" stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="student_name" label="学生姓名" width="120" />
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="class_name" label="班级" width="100" />
        <el-table-column prop="exam_title" label="考试名称" width="200" />
        <el-table-column prop="score" label="分数" width="100">
          <template #default="{ row }">
            <span :class="getScoreClass(row.score)">{{ row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total_score" label="满分" width="80" />
        <el-table-column label="得分率" width="100">
          <template #default="{ row }">
            {{ Math.round((row.score / row.total_score) * 100) }}%
          </template>
        </el-table-column>
        <el-table-column prop="rank" label="排名" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submit_time" label="提交时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.submit_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="viewDetail(row)">
              查看详情
            </el-button>
            <el-button size="small" type="warning" @click="adjustScore(row)">
              调整分数
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Download,
  User,
  Trophy,
  TrendCharts,
  Clock
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const examResults = ref([])
const exams = ref([])
const classes = ref([])

// 筛选表单
const filterForm = reactive({
  examId: null,
  classId: null,
  minScore: null,
  maxScore: null
})

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

// 统计数据
const statistics = ref([
  {
    label: '参考人数',
    value: 0,
    icon: User
  },
  {
    label: '平均分',
    value: 0,
    icon: TrendCharts
  },
  {
    label: '及格率',
    value: '0%',
    icon: Trophy
  },
  {
    label: '最高分',
    value: 0,
    icon: Clock
  }
])

// 获取成绩数据
const fetchExamResults = async () => {
  loading.value = true
  try {
    // TODO: 实现实际的API调用
    // const response = await examApi.getResults()

    // 模拟数据
    examResults.value = [
      {
        id: 1,
        student_name: '张三',
        student_id: '2024001',
        class_name: '一班',
        exam_title: '期中数学考试',
        score: 85,
        total_score: 100,
        rank: 5,
        status: '已批改',
        submit_time: '2024-01-19 14:30:00'
      },
      {
        id: 2,
        student_name: '李四',
        student_id: '2024002',
        class_name: '一班',
        exam_title: '期中数学考试',
        score: 92,
        total_score: 100,
        rank: 2,
        status: '已批改',
        submit_time: '2024-01-19 14:25:00'
      }
    ]

    // 计算统计数据
    const totalStudents = examResults.value.length
    const averageScore = Math.round(
      examResults.value.reduce((sum, result) => sum + result.score, 0) / totalStudents
    )
    const passCount = examResults.value.filter(result => result.score >= 60).length
    const passRate = Math.round((passCount / totalStudents) * 100)
    const maxScore = Math.max(...examResults.value.map(result => result.score))

    statistics.value[0].value = totalStudents
    statistics.value[1].value = averageScore
    statistics.value[2].value = `${passRate}%`
    statistics.value[3].value = maxScore

    pagination.total = examResults.value.length
  } catch (error) {
    console.error('获取成绩数据失败:', error)
    ElMessage.error('获取成绩数据失败')
  } finally {
    loading.value = false
  }
}

// 获取基础数据
const fetchBaseData = async () => {
  try {
    // TODO: 实现实际的API调用
    exams.value = [
      { id: 1, title: '期中数学考试' },
      { id: 2, title: '英语听力测试' }
    ]

    classes.value = [
      { id: 1, name: '一班' },
      { id: 2, name: '二班' }
    ]
  } catch (error) {
    console.error('获取基础数据失败:', error)
  }
}

// 筛选成绩
const filterResults = () => {
  // TODO: 实现筛选逻辑
  fetchExamResults()
}

// 重置筛选
const resetFilter = () => {
  Object.assign(filterForm, {
    examId: null,
    classId: null,
    minScore: null,
    maxScore: null
  })
  fetchExamResults()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchExamResults()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchExamResults()
}

// 查看详情
const viewDetail = (result: any) => {
  // TODO: 跳转到成绩详情页面
  console.log('查看成绩详情:', result)
}

// 调整分数
const adjustScore = (result: any) => {
  // TODO: 打开分数调整对话框
  console.log('调整分数:', result)
}

// 导出成绩
const exportResults = () => {
  // TODO: 实现成绩导出功能
  ElMessage.info('成绩导出功能开发中')
}

// 工具函数
const getScoreClass = (score: number) => {
  if (score >= 90) return 'excellent-score'
  if (score >= 80) return 'good-score'
  if (score >= 60) return 'pass-score'
  return 'fail-score'
}

const getStatusType = (status: string) => {
  switch (status) {
    case '已批改': return 'success'
    case '待批改': return 'warning'
    case '未提交': return 'danger'
    default: return 'info'
  }
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

onMounted(async () => {
  await fetchBaseData()
  await fetchExamResults()
})
</script>

<style scoped lang="scss">
.exam-result {
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    color: #303133;
  }
}

.stats-row {
  margin-bottom: 20px;

  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      padding: 16px;

      .stat-icon {
        margin-right: 16px;
        color: #409eff;
      }

      .stat-info {
        .stat-number {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 4px;
        }

        .stat-label {
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
}

.filter-card {
  margin-bottom: 20px;
}

.result-list-card {
  h3 {
    margin: 0;
    color: #303133;
  }

  .excellent-score { color: #67c23a; font-weight: bold; }
  .good-score { color: #409eff; }
  .pass-score { color: #e6a23c; }
  .fail-score { color: #f56c6c; }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>